<template>
  <div class="apply">
    <!-- 表单 -->
    <NavBar title="出差申请" left-arrow @click-left="onClickLeft" />
    <Form @submit="onSubmit" :scroll-to-error="true">
      <CellGroup class="pb" inset>
        <!-- 出差人 -->
        <div class="avter">
          <Cell>
            <div class="user-w">
              <span class="req"> 添加出差人 </span>
              <div class="user" v-for="(item, index) in fellowUserList" :key="index">
                <Image radius="5" round class="imgs" width="0.9rem" height="0.9rem" :src="item.img" />
                <Icon v-if="item.isLock" color="#1989fa" class="lock" name="lock" />
                <Icon v-else @click="closeFellowUser(index)" color="#1989fa" class="lock" name="close" />
                <div v-if="item.userName" class="f13">{{ item.userName }}</div>
              </div>
              <!-- 新增user弹窗 -->
              <Icon @click="addFellowUser" v-if="fellowUserList?.length != 1" class="i" size="30" name="plus" />
            </div>
          </Cell>
        </div>
        <!--  客户 -->
        <Field
          autosize
          type="textarea"
          v-model="customerName"
          required
          is-link
          readonly
          name="picker"
          label="客户联系人"
          placeholder="请选择"
          @click="changeCustomerUser"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerCust" :style="{ height: '40%' }" position="bottom">
          <div style="display: flex; align-items: center">
            <Search style="width: 85%" v-model="customerName" @update:model-value="searchCustomerName" placeholder="请输入客户联系人" />
            <Button size="small" @click="onConfirmCustom()" type="primary">确认</Button>
          </div>
          <Cell v-if="columnsCustomer?.length > 0" class="dept" v-for="(item, index) in columnsCustomer" :key="index">
            <Checkbox @change="setState" v-model="item.checked">
              <div class="user">
                <div class="user-items">
                  <span class="name" v-if="item.name">{{ item?.name }} </span>
                </div>
              </div>
            </Checkbox>
          </Cell>
          <Empty v-else class="mt3" image-size="3rem" image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" description="暂无客户数据" />
        </Popup>

        <!-- 出差事由 -->
        <Field autosize type="textarea" required :rules="[{ required: true, message: '请选择' }]" v-model="form.reason" name="出差事由" label="出差事由" placeholder="请输入" />

        <!-- 交通工具 -->
        <Field
          v-model="form.trafficType"
          is-link
          required
          readonly
          name="picker"
          label="交通工具"
          placeholder="点击选择交通工具"
          @click="showPickerCar = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerCar" position="bottom">
          <Picker :columns="columnsCar" @confirm="onConfirmCar" @cancel="showPickerCar = false" />
        </Popup>

        <!-- 单程往返 -->
        <Field
          v-model="form.isOneWay"
          is-link
          required
          readonly
          name="picker"
          label="单程往返"
          placeholder="点击选择单程往返"
          @click="showPickerTel = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerTel" position="bottom">
          <Picker :columns="columnsTel" @confirm="onConfirmTel" @cancel="showPickerTel = false" />
        </Popup>

        <!-- 出发城市 -->
        <Field
          v-model="form.departure"
          is-link
          required
          readonly
          name="picker"
          label="出发城市"
          placeholder="点击选择出发城市"
          @click="showPickerGo = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerGo" position="bottom">
          <Area title="出发城市" :columns-num="2" :area-list="areaList" value="440300" @confirm="onConfirmGo" @cancel="showPickerGo = false" />
        </Popup>

        <!-- 目的城市 -->
        <Field
          v-model="form.destination"
          is-link
          required
          readonly
          name="picker"
          label="目的城市"
          placeholder="点击选择目的城市"
          @click="showPickerTo = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerTo" position="bottom">
          <Area title="目的城市" :columns-num="2" :area-list="areaList" value="440300" @confirm="onConfirmTo" @cancel="showPickerTo = false" />
        </Popup>

        <!-- 开始时间 -->
        <Field v-model="form.stateTime" is-link required readonly name="picker" label="开始时间" placeholder="请选择" @click="showPickerTime = true" :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerTime" position="bottom">
          <DatetimePicker @confirm="onConfirmTime" @cancel="showPickerTime = false" v-model="currentDate" type="date" title="选择年月日" />
        </Popup>

        <!-- 结束时间 -->
        <Field
          :disabled="!form.stateTime"
          v-model="form.endTime"
          is-link
          required
          readonly
          name="picker"
          label="结束时间"
          placeholder="请选择"
          @click="showPickerTime1 = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerTime1" position="bottom">
          <DatetimePicker @confirm="onConfirmTime1" @cancel="showPickerTime1 = false" v-model="currentDate" type="date" title="选择年月日" />
        </Popup>

        <Field type="number" disabled v-model="form.duration" required name="出差天数" label="出差天数" placeholder="自动计算" />

        <!-- 成本中心 -->
        <Field
          v-model="form.costCenter"
          is-link
          required
          readonly
          name="picker"
          label="成本中心"
          placeholder="点击选择成本中心"
          @click="showPickerCbzx = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerCbzx" position="bottom">
          <Picker :columns="columnsCbzx" @confirm="onConfirmCbzx" @cancel="showPickerCbzx = false" />
        </Popup>

        <!-- 发票抬头 -->
        <Field
          v-model="form.invoice"
          is-link
          required
          readonly
          name="picker"
          label="发票抬头"
          placeholder="点击选择发票抬头"
          @click="showPickerCard = true"
          :rules="[{ required: true, message: '请选择' }]" />
        <Popup v-model:show="showPickerCard" position="bottom">
          <Picker :columns="columnsCbzx" @confirm="onConfirmCard" @cancel="showPickerCard = false" />
        </Popup>

        <!-- 同行人 -->
        <Field v-model="form.peers" name="同行人" label="同行人" placeholder="请输入同行人的名字" />

        <Field v-model="form.remark" type="textarea" autosize name="出差备注" label="出差备注" placeholder="出差备注" />

        <!-- 审批流程 -->
        <div class="vertical">
          <Cell title="审批流程" value="" />
          <Steps direction="vertical" :active="0">
            <Step>
              <div class="centers">
                <div>
                  <div>抄送人</div>
                  <div class="totle">抄送({{ userList?.length }})人</div>
                </div>
                <div class="avter">
                  <Cell>
                    <div class="user-w">
                      <div class="user" v-for="(item, index) in userList" :key="index">
                        <Image radius="5" round class="imgs" width="0.9rem" height="0.9rem" :src="item.img" />
                        <Icon v-if="item.isLock" color="#1989fa" class="lock" name="lock" />
                        <Icon v-else @click="closeUser(index)" color="#1989fa" class="lock" name="close" />
                        <div v-if="item.userName" class="f13">{{ item.userName }}</div>
                      </div>
                      <!-- 新增user弹窗 -->
                      <Icon @click="addUser" class="i" size="30" name="plus" />
                    </div>
                  </Cell>
                </div>
              </div>
            </Step>
            <Step>
              <div class="centers">
                <div>
                  <div>直属领导</div>
                  <div class="totle">请选择审批人</div>
                </div>
                <div class="avter">
                  <Cell>
                    <div class="user-w">
                      <div class="user" v-for="(item, index) in listCto" :key="index">
                        <Image radius="5" round class="imgs" width="0.9rem" height="0.9rem" :src="item.img" />
                        <Icon v-if="item.isLock" color="#1989fa" class="lock" name="lock" />
                        <Icon v-else @click="closeUser1(index)" color="#1989fa" class="lock" name="close" />
                        <div v-if="item.userName" class="f13">{{ item.userName }}</div>
                      </div>
                      <!-- 新增user弹窗 -->
                      <Icon v-if="listCto.length < 1" @click="addUserCto" class="i" size="30" name="plus" />
                    </div>
                  </Cell>
                </div>
              </div>
            </Step>
            <Step>
              <div class="centers">
                <div>
                  <div>审批人</div>
                  <div class="totle">1人审批</div>
                </div>
                <div class="avter">
                  <Cell>
                    <div class="user-w">
                      <div class="user" v-for="(item, index) in HXLlist" :key="index">
                        <Image radius="5" round class="imgs" width="0.9rem" height="0.9rem" :src="item.img" />
                        <Icon v-if="item.isLock" color="#1989fa" class="lock" name="lock" />
                        <div v-if="item.userName" class="f13">{{ item.userName }}</div>
                      </div>
                    </div>
                  </Cell>
                </div>
              </div>
            </Step>
          </Steps>
        </div>
      </CellGroup>
      <div class="m16">
        <Button round size="small" type="primary" class="btn" native-type="submit" @click="set(1)"> 提交 </Button>
        <Button round size="small" type="warning" class="btn" native-type="submit" @click="set(0)"> 存草稿 </Button>
      </div>
    </Form>

    <!-- 人员弹窗 -->
    <VanDialog v-model:show="show" :closeOnClickOverlay="true" :showConfirmButton="false" title="深圳市斯贝达电子有限公司">
      <User :isType="isType" @back="back" @callback="setCheckUser"></User>
    </VanDialog>
  </div>
</template>
<script setup name="apply">
import { ref, reactive, onMounted } from "vue";
import { Cell, Button, Checkbox, Form, Field, NavBar, Popup, Picker, CellGroup, Image, Steps, Step, Icon, Area, DatetimePicker, Search, Toast, Dialog, Empty } from "vant";
import { useRouter, useRoute } from "vue-router";

import { Local } from "@/utils/storage";
import { setTime, userLockList } from "@/utils/index";

// 省市区
import { areaList } from "@vant/area-data";

import User from "@/views/user/index.vue";

import { getCustomListUser, addTripPlan, getTripPlanById, updateTripPlan } from "@/api/index";

const router = useRouter();
const route = useRoute();

const VanDialog = Dialog.Component;

const userList = ref([]);
const listCto = ref([]);
const fellowUserList = ref([]);

const show = ref(false);
const isType = ref(null);
// 审批人
const HXLlist = ref([
  {
    userName: "韩晓兰",
    img: "https://static-legacy.dingtalk.com/media/lADPBG1Q5KlyowjNEYDNEYA_4480_4480.jpg",
    userId: "16068715551905448",
    isLock: true,
  },
]);

const form = reactive({
  customerID: undefined,
  reason: "",
  remark: "",
  costCenter: "深圳市斯贝达电子有限公司",
  invoice: "深圳市斯贝达电子有限公司",
  peers: "", //同行人
  cTo: "cTo", //
  leader: "", //直属领导审批
  userId: "", // 出差人
  createUserId: Local.get("userId"),
  //userName: Local.get("userName") || "张文强", || "16774612299105815"
});

// 初始化数据
onMounted(async () => {
  if (userList.value?.length == 0) {
    userList.value = userLockList;
  }
  if (fellowUserList.value?.length == 0) {
    fellowUserList.value = [
      {
        userName: Local.get("userName"),
        img: Local.get("userImg"),
        userId: Local.get("userId"),
      },
    ];
  }

  // 编辑的时候
  if (route.query.id) {
    console.log("编辑", route.query.id);
    getInfoById(route.query.id);
  }
});

const onClickLeft = () => {
  router.go(-1);
};

// 编辑回显
const getInfoById = async (id) => {
  let { data } = await getTripPlanById({ id });
  customerName.value = data.customerName;
  // 回显发送的人 过滤原本固定的成员
  const result = data.sendToJson.filter((obj1) => !userLockList.some((obj2) => obj2.userId === obj1.userId));
  userList.value = [...userLockList, ...result];
  fellowUserList.value = [data.userJson];
  listCto.value = [data.leaderJson];

  Object.assign(form, data);
  console.log(form);
};

// 区别是草稿 还是 提交
const set = (num) => {
  form.state = num;
};

//返回
const back = () => {
  show.value = false;
};

// 交通工具
const showPickerCar = ref(false);
const columnsCar = ["飞机", "火车", "汽车", "其他"];
const onConfirmCar = (value) => {
  form.trafficType = value;
  showPickerCar.value = false;
};

// 单程往返
const showPickerTel = ref(false);
const columnsTel = ["单程", "往返"];
const onConfirmTel = (value) => {
  form.isOneWay = value;
  showPickerTel.value = false;
};

// 出发城市
const showPickerGo = ref(false);
const onConfirmGo = (value) => {
  // 只保留市
  const are = value[1]?.name;
  form.departure = are;
  showPickerGo.value = false;
};

// 目的城市
const showPickerTo = ref(false);
const onConfirmTo = (value) => {
  const are = value[1]?.name;
  form.destination = are;
  showPickerTo.value = false;
};

// 开始时间
const showPickerTime = ref(false);
const currentDate = ref(new Date());
const onConfirmTime = async (value) => {
  const startDateTime = new Date(setTime(value));
  const endDateTime = new Date(form.endTime);
  if (endDateTime < startDateTime) {
    return Toast("开始时间不能大于结束时间");
  }
  form.stateTime = await setTime(value);
  getDuration();

  showPickerTime.value = false;
};

// 结束时间
const showPickerTime1 = ref(false);
const onConfirmTime1 = async (value) => {
  const startDateTime = new Date(form.stateTime);
  const endDateTime = new Date(setTime(value));
  if (endDateTime < startDateTime) {
    return Toast("结束时间不能小于开始时间");
  }
  form.endTime = await setTime(value);
  getDuration();

  showPickerTime1.value = false;
};

// 获取出差天数
const getDuration = () => {
  if (!form.stateTime && !form.endTime) {
    return;
  }
  // 输入开始时间
  const startDateTime = new Date(form.stateTime);

  // 输入结束时间
  const endDateTime = new Date(form.endTime);

  // 计算时间间隔（毫秒数）
  const timeDiff = endDateTime - startDateTime;

  // 将时间间隔转换为天数
  let daysDiff = timeDiff / (1000 * 60 * 60 * 24) + 1;
  form.duration = Number(daysDiff);
};

// 成本中心
const showPickerCbzx = ref(false);
const columnsCbzx = ["深圳市斯贝达电子有限公司"];
const onConfirmCbzx = (value) => {
  form.costCenter = value;
  showPickerCbzx.value = false;
};

// 发票抬头
const showPickerCard = ref(false);
const onConfirmCard = (value) => {
  form.invoice = value;
  showPickerCard.value = false;
};

//获取客户列表数据
const columnsCustomer = ref([]);
const _getCustList = async (name) => {
  let { data } = await getCustomListUser({ name, type: Number(route.query.type), userId: fellowUserList.value[0]?.userId });
  columnsCustomer.value = data;
  let arr = form.customerID.split(",");
  columnsCustomer.value.map((v) => {
    arr.map((j) => {
      if (j == v.id) {
        v.checked = true;
      }
    });
  });
};

const setState = () => {
  let arr = [];
  let ids = [];
  columnsCustomer.value.map((v) => {
    if (v.checked) {
      arr.push(v.name);
      ids.push(v.id);
    }
  });
  customerName.value = arr.toString();
};

// 确认选择客户
const showPickerCust = ref(false);
const onConfirmCustom = (e) => {
  let arr = [];
  let ids = [];
  columnsCustomer.value.map((v) => {
    if (v.checked) {
      arr.push(v.name);
      ids.push(v.id);
    }
  });
  form.customerID = ids.toString();
  customerName.value = arr.toString();
  showPickerCust.value = false;
};

// 选择客户联系人
const changeCustomerUser = () => {
  if (fellowUserList.value?.length == 0) {
    return Toast("请选择出差人");
  }
  showPickerCust.value = true;
  _getCustList();
};

// 查询客户
const customerName = ref("");
const searchCustomerName = (e) => {
  _getCustList(e);
};

// 删除抄送人
const closeUser = (index) => {
  userList.value.splice(index, 1);
};

// 删除出差人员
const closeFellowUser = (index) => {
  fellowUserList.value.splice(index, 1);
  customerName.value = "";
  form.customerID = "";
};

// 删除领导
const closeUser1 = (index) => {
  listCto.value.splice(index, 1);
};

// 抄送人
const addUser = () => {
  show.value = true;
  isType.value = 2;
};

// 直属领导
const addUserCto = () => {
  show.value = true;
  isType.value = 1;
};

// 设置出差人员
const addFellowUser = () => {
  show.value = true;
  isType.value = 3;
};

// 过滤
const filterList = (arr, ARR) => {
  return arr.filter((obj1) => !ARR.some((obj2) => obj2.userId === obj1.userId));
};
// 设置人员
const setCheckUser = (e) => {
  console.log(isType.value);
  if (isType.value == 3) {
    const result = filterList(e, fellowUserList.value);
    fellowUserList.value = [...fellowUserList.value, ...result];
  } else if (isType.value == 1) {
    listCto.value = e;
  } else {
    const res = filterList(e, userList.value);
    userList.value = [...userList.value, ...res];
  }
  show.value = false;
};

// 提交
const onSubmit = async () => {
  //直属领导
  form.leader = listCto.value[0]?.userId;
  if (!form.leader) {
    return Toast("直属领导不能为空");
  }
  // 抄送人
  form.cTo = userList.value
    .map((v) => {
      return v.userId;
    })
    .toString();
  // 出差人
  form.userId = fellowUserList.value
    .map((v) => {
      return v.userId;
    })
    .toString();
  form.type = Number(route.query.type);
  let res;
  if (route.query.id) {
    delete form.leaderJson;
    delete form.peersJson;
    delete form.createTime;
    delete form.sendToJson;
    delete form.updateTime;
    form.id = route.query.id;
    res = await updateTripPlan(form);
  } else {
    res = await addTripPlan(form);
  }
  if (res.code == 200) {
    Toast(`${route.query.id ? "编辑" : "新增"}成功`);
    router.go(-1);
  }
};
</script>
<style>
@import "../../../assets/styles/index.scss";
</style>
<style lang="scss" scoped>
@import "../index.scss";
</style>
